/*************************************************************************
	> File Name: test4.cc
	> Author: H.M. Lau
	> Mail: hm.lau@outlook.com
	> Created Time: 2023/09/19 14:02
 ************************************************************************/

#include <iostream>
#include <sys/types.h>
#include <signal.h>
#include <functional>
#include <vector>
#include <sys/wait.h>

typedef std::function<void ()> func;
std::vector<func> callbacks;

uint64_t count = 0;

void showLog()
{
    std::cout << "This is the function of logging." << std::endl;
}

void showCount()
{
    std::cout << "Final count:" << count << std::endl;
}

void logUser()
{
    if (fork() == 0) {
        execl("usr/bin/who", "who", nullptr);
        exit(1);
    }
    wait(nullptr);
}

void catchSig(int proc)
{
    for (auto &f : callbacks) {
        f();
    }
    alarm(1);
}

int main(int argc, char *argv[])
{
    signal(SIGALRM, catchSig);
    alarm(1);
    callbacks.push_back(showCount);
    callbacks.push_back(showLog);
    callbacks.push_back(logUser);
    while (1) {
        ++count;
    }
    return 0;
}
